var year = 2014;//年份

var beginMonth = 0;
var endMonth = 11;
var widthPerDay = 17;
DAY_IN_MILLISECONDS = 86400000;
var offsetPerClick = 800;
var currentWidth = widthPerDay * 5;
var circelRa = 4;

$(function() {

    var events = [{
        dates : new Date(2014, 0, 5), //注意月份是从0开始的
        title : "炉石战队大胜韩国选手",
        eventUrl : "#1"
    }, {
        dates : new Date(2014, 3, 29),
        title : "炉石战队大胜韩国选手",
        picUrl : "img/event_pic1.jpg",
        eventUrl : "#2"
    }, {
        dates : new Date(2014, 4, 9),
        title : "炉石战队大胜韩国选手",
        eventUrl : "#3"
    }, {
        dates : new Date(2014, 2, 5),
        title : "炉石战队大胜韩国选手",
        picUrl : "img/event_pic1.jpg",
        eventUrl : "#4"
    }, {
        dates : new Date(2014, 11, 5),
        title : "炉石战队大胜韩国选手",
        picUrl : "img/event_pic1.jpg",
        eventUrl : "#4"
    }];

    var myTimeline = new timeline($("#yearEvents"), events);








    //初始化body背景,与top位置
    window.onresize = function() {
        var offset = 1500 - ($("#page")[0].offsetLeft + $("#page").outerWidth());
        var back = "-" + offset + "px 0px";

        $("body").css({
            "background-position" : back
        });

    };

    window.onresize();
})
var timeline = function(main, events) {
    this.main = main;
    //最顶层jquery对象
    this.svgWrapper = null;
    this.svg = null;
    this.eventsDom = null;
    this.paper = null;
    this.currentPosition = null;
    this.positionFlag = false;
    //记录是否在滑块内按下鼠标

    this.events = events;
    //初始化参数
    this.beginMonth = beginMonth;
    this.endMonth = endMonth;
    this.begin = new Date(year, this.beginMonth, 1);
    this.end = new Date(year, this.endMonth, 1);

    this.widthPerDay = widthPerDay;
    this.count = 0;

    this.initDom();
    this.drawLines();
    this.initEvents();
    this.initClick();
}

timeline.prototype.initDom = function() {
    handle = this;
    //初始化dom树
    var svgWrapper = $("<div class='svgWrapper'></div>");
    this.main.append(svgWrapper);
    this.svgWrapper = svgWrapper;

    var eventsWrapper = $("<div class='eventsWrapper'></div>");
    var events = $("<div class='events'></div>");
    eventsWrapper.append(events);

    this.main.append(eventsWrapper);

    this.eventsDom = events;

    this.paper = Raphael(this.svgWrapper[0], 100000, 82);
    this.svg = this.svgWrapper.find("*:eq(0)");
    this.svg.css({
        "position" : "relative",
        "left" : "0px",
        "height" : "82px",
        "width" : "10000px",
        "background-color" : "rgb(26,18,38)",
        "-webkit-transition" : "left .3s ease-out",
        "-moz-transition" : "left .3s ease-out",
        "-o-transition" : "left .3s ease-out",
        "transition" : "left .3s ease-out"
    })

    var position = this.paper.rect(this.widthPerDay, 0, currentWidth, 81, 10);

    position.attr({
        "fill" : "rgba(107,26,107,0.3)",
        "stroke-width" : 2,
        "stroke" : "red"
    });



    this.currentPosition = position;

    $(position.node).addClass("currentPosition");
    $(position.node).css({
        "cursor" : "pointer"
    });
    //this.svg.append($(position.node));

    var IE = null;
    if($.browser.msie && ($.browser.version == "7.0")) {
        IE = 7;
    }
    if($.browser.msie && ($.browser.version == "8.0")) {
        IE = 8;
    }
    if($.browser.msie && ($.browser.version == "6.0")) {
        IE = 6;
    }

    if(IE && IE <= 8) {
        $(position.node).hide();
    }

    //四个按钮
    var eventsLeft = $('<div class="eventsLeft"><img src="img/eventsLeft.png" /></div>');
    var eventsRight = $('<div class="eventsRight"><img src="img/eventsRight.png" /></div>');
    var timeLineLeft = $('<div class="timeLineLeft"><img src="img/timeLineLeft.png" /></div>');
    var timeLineRight = $('<div class="timeLineRight"><img src="img/timeLineRight.png" /></div>');

    var tips = $('<div class="tips"><span class="date"></span><span class="title"></span><span class="arrow"><a href="javascript:void(0)">◆</a></span></div>');

    this.main.append(eventsLeft).append(eventsRight).append(timeLineLeft).append(timeLineRight).append(tips);
}

timeline.prototype.drawLines = function() {
    var handle = this;
    for(var monthTemp = this.begin.getMonth(); monthTemp <= this.end.getMonth(); monthTemp++) {
        var temp = new Date(this.begin.getFullYear(), monthTemp + 1, 0);
        var dayCount = temp.getDate();

        for(var dayTemp = 0; dayTemp < dayCount; dayTemp++) {
            var thisYear = this.begin.getFullYear();
            var thisMonth = monthTemp + 1;
            var thisDay = dayTemp + 1;

            this.count++;

            //添加timeLine 标度尺
            var x1 = this.count * this.widthPerDay;
            var y1 = this.svg.height() - 2 - 30;
            var x2 = this.count * this.widthPerDay;

            if(dayTemp == 0) {// 每月第一天,划长线,加月份
                var y2 = this.svg.height() - 50;
                var t = this.paper.text(x1, y1 + 20, thisMonth + "月");
                t.attr({
                    "fill" : "rgb(200,173,120)"
                });
            } else {
                var y2 = this.svg.height() - 40;
            }

            var string = "M" + x1 + " " + y1 + "L" + x2 + " " + y2;
            var p = this.paper.path(string);

            //console.log(string);
            p.attr({
                "stroke-width" : 2,
                "stroke" : "rgb(200,173,120)"
            });

            $(p.node).attr("data-type", "path");
            //添加events中的oneDay

            var $oneDay = $("<div class='oneDay'></div>");
            if(this.count % 2 == 1) {
                $oneDay.addClass("odd");
            }
            var $oneDayInner = $("<div class='oneDayInner'></div>");
            var $subDate = $("<div class='subDate'></div>");
            $subDate.append($("<span class='number'>" + thisDay + "</span>"));
            $subDate.append($("<span>th</span>"));
            $oneDayInner.append($subDate);
            $oneDay.append($oneDayInner);
            this.eventsDom.append($oneDay);
        }

    }

    //划刻度下方粗横线
    var string = "M" + 0 + " " + (this.svg.height() - 25) + "L" + (this.count * this.widthPerDay) + " " + (this.svg.height() - 25);
    var p = this.paper.path(string);

    p.attr({
        "stroke-width" : 8,
        "stroke" : "rgb(200,173,120)"
    });
    $(p.node).addClass("bottomLine");

    //console.log(string)

}

timeline.prototype.initEvents = function() {
    var handle = this;

    for(var i = 0; i < this.events.length; i++) {

        var thisDay = this.events[i]["dates"];
        var offsetDay = (thisDay - this.begin) / DAY_IN_MILLISECONDS + 1;
        var dateString = thisDay.getFullYear() + "-" + (thisDay.getMonth() + 1) + "-" + thisDay.getDate();
        //console.log(offsetDay)
        //添加timeline上的红点
        var cx = offsetDay * this.widthPerDay;
        var cy = this.svg.height() - 10 - (this.svg.find("*[data-x=" + cx + "]").length * (circelRa * 2.5)) - 25;
        //console.log(cy)
        //距离底部距离25 + 10
        var c = this.paper.circle(cx, cy, circelRa);

        c.attr({
            "stroke" : "red",
            "fill" : "red"
        });

        $(c.node).attr("data-x", cx);
        $(c.node).attr("data-title", this.events[i]["title"]);
        $(c.node).attr("data-date", dateString);
        $(c.node).addClass("circle");

        //注册circle事件
        c.click(function() {
            var left = $(this.node).attr("data-x");
            //console.log(left)

            left = (left / handle.widthPerDay - 2) * 200;

            //console.log(left)

            left = left < 0 ? 0 : left;
            left = left > (handle.count - 5) * 200 ? (handle.count - 5) * 200 : left;

            left = -left;
            handle.eventsDom.animate({
                left : left
            }, 300, function() {
                handle.refreshPosition();
            });
        });

        c.hover(function() {
            handle.main.find(".tips .date").text($(this.node).attr("data-date"));
            handle.main.find(".tips .title").text($(this.node).attr("data-title"));

            var length = handle.svg.find("*[data-x=" + ($(this.node).attr("data-x")) + "]").length ;

            var left = $(this.node).offset().left - handle.main.find(".tips").width() - handle.main.offset().left + 30;
            var top = handle.svgWrapper.offset().top - handle.main.offset().top - handle.main.find(".tips").height() - length*2*circelRa;
            handle.main.find(".tips").css({
                "left" : left,
                "top" : top
            });

            handle.main.find(".tips").fadeIn("fast");

        }, function() {
            setTimeout(function() {
                handle.main.find(".tips").fadeOut("fast");
            }, "3000");
        })
        //添加events day的事件

        var $oneDay = $(".oneDay:eq(" + (offsetDay - 1) + ")");
        var $event = $("<div class='event'></div>");
        var $picture = null;

        if(this.events[i]["picUrl"] == null) {
            $event.addClass("noPic")
        } else {
            $event.addClass("hasPic")
            $picture = $("<div class='picture'></div>");
            $picture.append($("<a href='" + this.events[i]["eventUrl"] + "'><img src =' " + this.events[i]["picUrl"] + "' /></a>"));
        }

        var $date = $("<div class='date'></div>");

        $date.text(dateString);

        var $title = $("<div class='title'><a href='" + this.events[i]["eventUrl"] + "'></a></div>");
        $title.find("a").text(this.events[i]["title"]);

        $event.append($date).append($title).append($picture);

        $oneDay.find(".oneDayInner .subDate").before($event);
    }
}

timeline.prototype.refreshPosition = function() {

    var eventsLeft = this.eventsDom.position().left;

    var offsetDay = (Math.abs(eventsLeft) / 200);

    var currentLeft = offsetDay * this.widthPerDay;

    currentLeft = currentLeft > this.widthPerDay ? currentLeft : this.widthPerDay;

    this.currentPosition.animate({
        "x" : currentLeft
    },300);

    //timeline移动
    var timelineLeft = offsetDay / this.count * (1000 - this.currentPosition.attr("width"));
    timelineLeft = currentLeft - timelineLeft;
    timelineLeft = -timelineLeft;

    this.svg.animate({
        left : timelineLeft
    }, 300);

}

timeline.prototype.initClick = function() {
    var handle = this;

    handle.main.find(".eventsLeft").click(function() {
        var left = handle.eventsDom.position().left + 1000;
        left = left > 0 ? 0 : left;

        handle.eventsDom.animate({
            left : left
        }, 300, function() {
            handle.refreshPosition();
        });

    });

    handle.main.find(".eventsRight").click(function() {
        var left = handle.eventsDom.position().left - 1000;
        var mostLeft = -(handle.count * 200 - handle.eventsDom.parent().width());

        left = left < mostLeft ? mostLeft : left;
        left = left > 0 ? 0 : left;

        handle.eventsDom.animate({
            left : left
        }, 300, function() {
            handle.refreshPosition();
        });

    });

    handle.main.find(".timeLineLeft").click(function() {
        var svgLeft = handle.svg.offset().left - handle.svgWrapper.offset().left;

        var left = svgLeft + offsetPerClick;
        left = left > 0 ? 0 : left;

        handle.svg.animate({
            left : left
        }, 300);

    })

    handle.main.find(".timeLineRight").click(function() {
        var svgLeft = handle.svg.offset().left - handle.svgWrapper.offset().left;

        var left = svgLeft - offsetPerClick;
        var mostLeft = -(handle.count * widthPerDay - handle.svgWrapper.width());

        left = left < mostLeft ? mostLeft : left;
        left = left > 0 ? 0 : left;

        handle.svg.animate({
            left : left
        }, 300);

    })
    
    
    var position = handle.currentPosition;
    
    position.mousedown(function(e) {
        handle.positionFlag = true;
        
        e.preventDefault();
    });

    position.mousemove(function(e) {
        
        if(handle.positionFlag == false) {
            return;
        }
        
        var left = (e.layerX - position.attr("width") / 2) / handle.widthPerDay * 200;
        left = left > (handle.count -5) * 200 ? (handle.count -5) * 200 : left;
        left = -left;
        left = left > 0 ? 0 : left;

        handle.eventsDom.css({
            left : left
        });

        position.attr({
            "x" : -(left / 200 * handle.widthPerDay)
        });
        e.preventDefault();
    })

    position.mouseup(function(e) {
        handle.positionFlag = false;
        e.preventDefault();
    })

    position.mouseout(function() {
        handle.positionFlag = false;
    })    
    
    
    this.svg.append($(position.node));
    
    
}

